// HTML PPT 导航脚本 - 核心功能请勿修改

class HTMLPresentation {
    constructor() {
        this.currentSlide = 1;
        this.totalSlides = 3;
        this.init();
    }

    init() {
        this.setupEventListeners();
        this.updateIndicators();
    }

    setupEventListeners() {
        // 键盘导航
        document.addEventListener('keydown', (e) => {
            switch(e.key) {
                case 'ArrowRight':
                case ' ': // 空格键
                    e.preventDefault();
                    this.nextSlide();
                    break;
                case 'ArrowLeft':
                    e.preventDefault();
                    this.prevSlide();
                    break;
                case 'Home':
                    e.preventDefault();
                    this.goToSlide(1);
                    break;
                case 'End':
                    e.preventDefault();
                    this.goToSlide(this.totalSlides);
                    break;
                case 'Escape':
                    this.exitFullscreen();
                    break;
                case 'F11':
                case 'f':
                    e.preventDefault();
                    this.toggleFullscreen();
                    break;
            }
        });

        // 移除鼠标点击导航，避免误触发
        // 保留原代码作为注释，如需要可以重新启用
        /*
        document.addEventListener('click', (e) => {
            // 点击右半部分前进，左半部分后退
            const clickX = e.clientX;
            const screenWidth = window.innerWidth;
            
            if (clickX > screenWidth / 2) {
                this.nextSlide();
            } else {
                this.prevSlide();
            }
        });
        */

        // 鼠标滚轮导航
        document.addEventListener('wheel', (e) => {
            e.preventDefault();
            if (e.deltaY > 0) {
                this.nextSlide();
            } else {
                this.prevSlide();
            }
        }, { passive: false });

        // 指示器点击
        document.querySelectorAll('.indicator-dot').forEach((dot, index) => {
            dot.addEventListener('click', (e) => {
                e.stopPropagation();
                this.goToSlide(index + 1);
            });
        });

        // 阻止链接和按钮的默认点击行为冲突
        document.querySelectorAll('a, button').forEach(element => {
            element.addEventListener('click', (e) => {
                e.stopPropagation();
            });
        });

        // 触摸设备支持
        this.setupTouchNavigation();
    }

    setupTouchNavigation() {
        let startX = 0;
        let startY = 0;
        
        document.addEventListener('touchstart', (e) => {
            startX = e.touches[0].clientX;
            startY = e.touches[0].clientY;
        });

        document.addEventListener('touchend', (e) => {
            if (!startX || !startY) return;

            let endX = e.changedTouches[0].clientX;
            let endY = e.changedTouches[0].clientY;

            let diffX = startX - endX;
            let diffY = startY - endY;

            // 判断是否为有效滑动
            if (Math.abs(diffX) > Math.abs(diffY) && Math.abs(diffX) > 50) {
                if (diffX > 0) {
                    this.nextSlide(); // 向左滑动，下一页
                } else {
                    this.prevSlide(); // 向右滑动，上一页
                }
            }

            startX = 0;
            startY = 0;
        });
    }

    nextSlide() {
        if (this.currentSlide < this.totalSlides) {
            this.goToSlide(this.currentSlide + 1);
        }
    }

    prevSlide() {
        if (this.currentSlide > 1) {
            this.goToSlide(this.currentSlide - 1);
        }
    }

    goToSlide(slideNumber) {
        if (slideNumber < 1 || slideNumber > this.totalSlides) return;

        const direction = slideNumber > this.currentSlide ? 'next' : 'prev';
        
        // 移除所有状态类
        document.querySelectorAll('.slide').forEach(slide => {
            slide.classList.remove('active', 'prev', 'next');
        });

        // 设置当前幻灯片
        const currentSlideElement = document.getElementById(`slide-${slideNumber}`);
        currentSlideElement.classList.add('active');

        // 设置其他幻灯片的状态（齿轮布局）
        for (let i = 1; i <= this.totalSlides; i++) {
            if (i !== slideNumber) {
                const slide = document.getElementById(`slide-${i}`);
                if (i < slideNumber) {
                    slide.classList.add('prev');
                } else {
                    slide.classList.add('next');
                }
            }
        }

        this.currentSlide = slideNumber;
        this.updateIndicators();
        this.announceSlideChange();
    }

    updateIndicators() {
        document.querySelectorAll('.indicator-dot').forEach((dot, index) => {
            if (index + 1 === this.currentSlide) {
                dot.classList.add('active');
            } else {
                dot.classList.remove('active');
            }
        });
    }

    announceSlideChange() {
        // 为屏幕阅读器提供反馈
        const announcement = `第 ${this.currentSlide} 页，共 ${this.totalSlides} 页`;
        this.announce(announcement);
    }

    announce(message) {
        const announcer = document.createElement('div');
        announcer.setAttribute('aria-live', 'polite');
        announcer.setAttribute('aria-atomic', 'true');
        announcer.style.position = 'absolute';
        announcer.style.left = '-10000px';
        announcer.style.width = '1px';
        announcer.style.height = '1px';
        announcer.style.overflow = 'hidden';
        announcer.textContent = message;
        document.body.appendChild(announcer);
        
        setTimeout(() => {
            document.body.removeChild(announcer);
        }, 1000);
    }

    toggleFullscreen() {
        if (!document.fullscreenElement) {
            document.documentElement.requestFullscreen().catch(err => {
                console.log(`无法进入全屏模式: ${err.message}`);
            });
        } else {
            document.exitFullscreen();
        }
    }

    exitFullscreen() {
        if (document.fullscreenElement) {
            document.exitFullscreen();
        }
    }

    // 获取当前幻灯片信息（供外部调用）
    getCurrentSlideInfo() {
        return {
            current: this.currentSlide,
            total: this.totalSlides,
            percentage: Math.round((this.currentSlide / this.totalSlides) * 100)
        };
    }
}

// Demo跳转函数 - 可以自定义修改
function openDemo() {
    // 当前演示：显示这个PPT本身就是Demo
    alert('🎉 这个PPT本身就是Demo展示！\n\n✨ 你现在看到的就是HTML PPT的效果\n🔄 尝试用键盘方向键或鼠标点击切换页面\n🖼️ 右上角画廊会自动轮播\n🔍 右下角组件可以点击放大\n\n如需查看源码，请访问项目GitHub仓库');
    
    // 实际项目中，替换为你的Demo链接：
    // const demoUrl = 'https://your-demo-url.com';
    // window.open(demoUrl, '_blank');
}

// 组件画廊交互功能
class ComponentGallery {
    constructor(container) {
        this.container = container;
        this.items = container.querySelectorAll('.gallery-item');
        this.indicators = container.querySelectorAll('.gallery-indicators .indicator');
        this.prevBtn = container.querySelector('.gallery-btn.prev');
        this.nextBtn = container.querySelector('.gallery-btn.next');
        this.currentIndex = 0;
        
        this.init();
    }
    
    init() {
        // 绑定按钮事件
        this.prevBtn?.addEventListener('click', (e) => {
            e.stopPropagation();
            this.prev();
        });
        
        this.nextBtn?.addEventListener('click', (e) => {
            e.stopPropagation();
            this.next();
        });
        
        // 绑定指示器事件
        this.indicators.forEach((indicator, index) => {
            indicator.addEventListener('click', (e) => {
                e.stopPropagation();
                this.goTo(index);
            });
        });
        
        // 自动播放
        this.startAutoPlay();
    }
    
    prev() {
        this.goTo(this.currentIndex > 0 ? this.currentIndex - 1 : this.items.length - 1);
    }
    
    next() {
        this.goTo(this.currentIndex < this.items.length - 1 ? this.currentIndex + 1 : 0);
    }
    
    goTo(index) {
        if (index === this.currentIndex) return;
        
        // 移除当前活动状态
        this.items[this.currentIndex]?.classList.remove('active');
        this.indicators[this.currentIndex]?.classList.remove('active');
        
        // 设置新的活动状态
        this.currentIndex = index;
        this.items[this.currentIndex]?.classList.add('active');
        this.indicators[this.currentIndex]?.classList.add('active');
    }
    
    startAutoPlay() {
        setInterval(() => {
            this.next();
        }, 4000); // 4秒自动切换
    }
}

// 可展开组件功能
function toggleExpand(button) {
    const widget = button.closest('.expandable-widget');
    const isExpanded = widget.classList.contains('expanded');
    
    // 关闭所有其他展开的组件
    document.querySelectorAll('.expandable-widget.expanded').forEach(w => {
        if (w !== widget) {
            w.classList.remove('expanded');
        }
    });
    
    // 切换当前组件状态
    widget.classList.toggle('expanded');
    
    // 更新按钮图标
    button.textContent = widget.classList.contains('expanded') ? '✕' : '🔍';
    
    // 阻止事件冒泡
    event.stopPropagation();
}

// 点击空白区域关闭展开的组件
document.addEventListener('click', (e) => {
    if (!e.target.closest('.expandable-widget')) {
        document.querySelectorAll('.expandable-widget.expanded').forEach(widget => {
            widget.classList.remove('expanded');
            const button = widget.querySelector('.expand-btn');
            if (button) button.textContent = '🔍';
        });
    }
});

// 初始化演示文稿
const presentation = new HTMLPresentation();

// 页面加载完成后的额外设置
document.addEventListener('DOMContentLoaded', () => {
    // 初始化所有组件画廊
    document.querySelectorAll('.component-gallery').forEach(gallery => {
        new ComponentGallery(gallery);
    });
    
    // 隐藏导航提示（5秒后）
    setTimeout(() => {
        const hint = document.querySelector('.navigation-hint');
        if (hint) {
            hint.style.opacity = '0';
            setTimeout(() => {
                hint.style.display = 'none';
            }, 500);
        }
    }, 5000);

    // 阻止右键菜单（演示模式）
    document.addEventListener('contextmenu', (e) => {
        e.preventDefault();
    });

    // 阻止文本选择（演示模式）
    document.addEventListener('selectstart', (e) => {
        e.preventDefault();
    });
});

// 导出供外部使用
window.presentation = presentation;


